package jp.kiroru_inc.rs_hello_world;

import jp.kiroru_inc.rs_hello_world.R;
import jp.kiroru_inc.rs_hello_world.ScriptC_HelloWorldScript;

import android.content.Context;
import android.content.res.Resources;
import android.renderscript.Allocation;
import android.renderscript.Float2;
import android.renderscript.ProgramFragment;
import android.renderscript.ProgramFragmentFixedFunction;
import android.renderscript.ProgramRaster;
import android.renderscript.ProgramStore;
import android.renderscript.RenderScriptGL;
import android.renderscript.Sampler;

/**
 * @author Selphy
 */
public class HelloWorldScript {
	private ScriptC_HelloWorldScript script;
	
	private Allocation texture;
	private ProgramStore progStoreBlendAlpha;
	private ProgramFragment progFragmentTexture;
	private ProgramRaster cullNone;
	
	protected HelloWorldScript(RenderScriptGL rs, final Context c, Resources res) {
		script = new ScriptC_HelloWorldScript(rs, res, R.raw.helloworldscript);
		
		texture = Allocation.createFromBitmapResource(rs, res, R.drawable.droid_yellow);
		script.set_texture(texture);

		// ProgramStore
		// 　Alpha値を有効にする。
		progStoreBlendAlpha = ProgramStore.BLEND_ALPHA_DEPTH_TEST(rs);
		script.set_gProgStoreBlendAlpha(progStoreBlendAlpha);

		// テクスチャー用のFragment
		// 　Samplerを設定してテクスチャーのジャギーを目立たなくする。
		ProgramFragmentFixedFunction.Builder texBuilder = new ProgramFragmentFixedFunction.Builder(rs);
		texBuilder.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.REPLACE, ProgramFragmentFixedFunction.Builder.Format.RGBA, 0);
		progFragmentTexture = texBuilder.create();
		progFragmentTexture.bindSampler(Sampler.CLAMP_LINEAR(rs), 0);
		script.set_gProgFragmentTexture(progFragmentTexture);

		// Raster
		// 　テクスチャーの表裏を描画する。
		cullNone = ProgramRaster.CULL_NONE(rs);
		script.set_gCullNone(cullNone);
		
		rs.bindRootScript(script);
	}
	
	protected void touchEvent(float x, float y) {
		script.invoke_setTouchPosition(new Float2(x, y));
	}
}